$(function () {
    var sid;
    $("#jqGrid").jqGrid({
        url: baseURL + 'water/tclientinfo/list',
        postData:{dept : ''},
        datatype: "json",
        colModel: [			
			{ label: '设备号', name: 'deviceId', index: 'device_id',  key: true },
			{ label: '表卡编号', name: 'clientId', index: 'client_id' },
			{ label: '客户名称', name: 'clientName', index: 'client_name' },
			//{ label: 'IMEI', name: 'clientIdCard', index: 'client_id_card', width: 180 },
            //{ label: 'SIM卡号', name: 'desc16', index: 'desc16', width: 180 },
            { label: '设备地址', name: 'clientDeviceInfo', index: 'device_id'
                ,formatter: function(value, options, row){
                    if (value == null) return "";
                    var cellvalue = value.masterNum + '-' + value.slaveNum + '-' + value.cardNum + '-' + value.routeNum + '-' + value.meterNum;
                    return cellvalue;
                }},
            { label: '小区名称', name: 'memo1', index: 'memo1',hidden:true },
            { label: '详细公安地址', name: 'proName', index: 'pro_name'
                ,formatter: function(value, options, row){
                    if (value == null) return "";

                    var cellvalue = row.memo1+'-'+ row.proName + '-'+ row.buildNum + '-' + row.unitNum + '-' + row.houseNum;
                    return cellvalue;
                }
            },
			//{ label: '楼号', name: 'buildNum', index: 'build_num'},
			//{ label: '单元', name: 'unitNum', index: 'unit_num'},
			//{ label: '门牌号码', name: 'houseNum', index: 'house_num'},

           // {label:'账本',name:'accountNo',index:'account_no'},
           // {label:'表卡编号',name:'searchNo',index:'search_no'},
            //{label:'电话',name:'phone',index:'phone'},
            //{label:'表号',name:'meterCode',index:'meter_code'},
            //{label:'封号',name:'stampCode',index:'stamp_code'},
            //{label:'口径',name:'calibre',index:'calibre'},
            //{label:'用户性质',name:'clientType',index:'client_type'},
           // {label:'设备代码',name:'deviceCode',index:'device_code'},
            //{label:'小楼号',name:'buildingNo',index:'building_no'},
            //{label:'楼层',name:'floorNo',index:'floor_no'},
            //{label:'其他码',name:'otherNo',index:'other_no'},

			{ label: '备注2', name: 'memo2', index: 'memo2', hidden:false },
			//{ label: '备注3', name: 'memo3', index: 'memo3', width: 80,hidden:true },
			//{ label: '二维码', name: 'qrcode', index: 'qrCode', width: 80,hidden:true },
            //{ label: 'desc4', name: 'desc4', index: 'desc4', width: 80,hidden:false },
        ],
		viewrecords: true,
        height: $(window).height() > 385 ?  $(window).height() - 130 : 385,
        rowNum: 55,
		rowList : [10,20,30,50,80,100,200],
        rownumbers: true, 
        rownumWidth: 65,
        autowidth: $(window).width() > 200 ? true : false ,
        //width:$(window).width() > 200 ? 1000 : 2000,
        multiselect: false,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        ondblClickRow: function(rowid, iRow, iCol, e){
            $("#jqGrid").jqGrid('resetSelection');
            //$("#jqGrid").jqGrid('setSelection',$("#selRow").val(),false);
            $("#jqGrid").jqGrid('setSelection',rowid);

            vm.openInfoLayer($("#jqGrid").jqGrid("getRowData", rowid));

            $('#myTab a:first').tab('show');
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });

            jQuery("#jqGrid").jqGrid('setLabel', 'rn', '序号', {
                'text-align': 'center',
                'vertical-align': 'middle',
                //"width": "50"
            });
            $("table[role='grid']").each(function () {//jqgrid 创建的表格都有role属性为grid
                $('.' + $(this).attr("class") + ' tr:first th:first').css("width", "50"); //使表头的序号列宽度为40
                $('.' + $(this).attr("class") + ' tr:first td:first').css("width", "50"); // 使表体的序号列宽度为40
            });

            const resizeEvent = new Event('resize');
            window.dispatchEvent(resizeEvent);

        },
        onSelectRow: function (rowid, status) {
            // 当前选中行，用于页面调用reloadJqGrid刷新后，继续选中之前选中的
            sid = rowid;
            vm.openInfoLayer($("#jqGrid").jqGrid("getRowData", rowid));
            $('#myTab a:first').tab('show');
        },
//页面调用reloadJqGrid刷新后，继续选中之前选中的
        loadComplete:function () {
            if (sid){
                $(this).jqGrid("setSelection",sid);
            }
        }
    });

    $(function () {
        $('#inputClear').click(function () {
            $('input')[0].value = "";
            vm.q.value="";
        })
    });

    $('#datetimepicker1,#datetimepicker2').datetimepicker({
        format: 'YYYY.MM.DD',
        locale: moment.locale('zh-cn')
    });
});

/*
function showMenu() {
    var cityObj = $("#citySel");
    var cityOffset = $("#citySel").offset();

    $("#menuContent").css(
        //{left:cityOffset.left + "px", top:cityOffset.top + cityObj.outerHeight() + "px"}
        {left:5+"px",top:40+"px"}
    ).slideDown("fast");

    $("#deptTreeLeft").css({width:(cityObj.width()+10)+"px"});

    $("body").bind("mousedown", onBodyDown);
}
function hideMenu() {
    $("#menuContent").fadeOut("fast");
    $("body").unbind("mousedown", onBodyDown);
}
function onBodyDown(event) {
    if (!(event.target.id == "menuBtn" || event.target.id == "menuContent" || $(event.target).parents("#menuContent").length>0)) {
        hideMenu();
    }
}

*/

function ZtreeBeforeClick(treeId, treeNode) {
    var check = (treeNode && !treeNode.isParent);
    if (!check) alert("只能选择小区...");
    return check;
}

function ZtreeOnClick(e, treeId, treeNode) {
    vm.q.dept = treeNode.deptId;
    vm.newpage = true;
    if(!treeNode.isParent) {
        var x = treeNode.deptId.split("_");
        if (x.length == 4){
            vm.q.dept = x[3];
        }
    }else{
        vm.q.dept='';
    }
}


function zTreeOnDblClick(event, treeId, treeNode) {
    vm.q.dept = treeNode.deptId;
    vm.newpage = true;
    if(!treeNode.isParent) {
        var x = treeNode.deptId.split("_");
        if (x.length == 4){
            vm.q.dept = x[3];
            vm.reload();
        }
    }else{
        vm.q.dept='';
    }
    //alert(treeNode.deptId);
    //alert(treeNode ? treeNode.tId + ", " + treeNode.name : "isRoot");
};

var settingLeft = {
    data: {
        simpleData: {
            enable: true,
            idKey: "deptId",
            pIdKey: "parentId",
            rootPId: -1
        },
        key: {
            url:"nourl"
        }
    },
    callback: {
        beforeClick: ZtreeBeforeClick,
        onClick: ZtreeOnClick,
        onDblClick: zTreeOnDblClick
    }
};

var ztree;

var vm = new Vue({
	el:'#rrapp',
	data:{
		showList: true,
		title: null,
		tClientInfo: {},
        newpage : false,
        searchKeyDictInfo: {},
        q:{
            key:null,
            value:null,
            dept:null
        },
        op:{
            ch:false,
        },
        clientMeterTypeInfo:{},
        clientUseInfo:{},
        clientFixAddrInfo:{},
        clientCalibre:{},
        clientDeviceInfo:{},

        progressbar : 0,
        currPer:0,

        startTime: '',
        endTime: ''
    },
	methods: {
        getSearchKeyDict: function(){
            $.get(baseURL + "sys/dict/list",{name:"qkey_tclientinfo"}, function(r){
                vm.searchKeyDictInfo = r.page.list;
            });

            //字典
            $.get(baseURL + "sys/dict/list",{name:"dict_device_type"}, function(r){
                vm.clientMeterTypeInfo = r.page.list;
            });

            $.get(baseURL + "sys/dict/list",{name:"dict_use_type"}, function(r){
                vm.clientUseInfo = r.page.list;
            });

            $.get(baseURL + "sys/dict/list",{name:"dict_fix_addr"}, function(r){
                vm.clientFixAddrInfo = r.page.list;
            });

            $.get(baseURL + "sys/dict/list",{name:"dict_calibre"}, function(r){
                vm.clientCalibre = r.page.list;
            });
        },
        query: function () {
            if(vm.q.value != null && vm.q.value != ""
                && (vm.q.key == null || vm.q.key == "")){
                alert('请选择查询条件!');
                return;
            }
            vm.newpage=true;

			vm.reload();
		},
		add: function(){
			vm.showList = false;
			vm.title = "新增";
			vm.tClientInfo = {};
		},
		update: function (event) {
			var deviceId = getSelectedRow();
			if(deviceId == null){
				return ;
			}
			vm.showList = false;
            vm.title = "修改";
            
            vm.getInfo(deviceId)
		},
		saveOrUpdate: function (event) {
		    $('#btnSaveOrUpdate').button('loading').delay(1000).queue(function() {
                var url = vm.tClientInfo.deviceId == null ? "water/tclientinfo/save" : "water/tclientinfo/update";
                $.ajax({
                    type: "POST",
                    url: baseURL + url,
                    contentType: "application/json",
                    data: JSON.stringify(vm.tClientInfo),
                    success: function(r){
                        if(r.code === 0){
                             layer.msg("操作成功", {icon: 1});
                             vm.newpage=false;
                             vm.reload();
                             $('#btnSaveOrUpdate').button('reset');
                             $('#btnSaveOrUpdate').dequeue();
                        }else{
                            layer.alert(r.msg);
                            $('#btnSaveOrUpdate').button('reset');
                            $('#btnSaveOrUpdate').dequeue();
                        }
                    }
                });
			});
		},
		del: function (event) {
			var deviceIds = getSelectedRows();
			if(deviceIds == null){
				return ;
			}
			var lock = false;
            layer.confirm('确定要删除选中的记录？', {
                btn: ['确定','取消'] //按钮
            }, function(){
               if(!lock) {
                    lock = true;
		            $.ajax({
                        type: "POST",
                        url: baseURL + "water/tclientinfo/delete",
                        contentType: "application/json",
                        data: JSON.stringify(deviceIds),
                        success: function(r){
                            if(r.code == 0){
                                layer.msg("操作成功", {icon: 1});
                                $("#jqGrid").trigger("reloadGrid");
                            }else{
                                layer.alert(r.msg);
                            }
                        }
				    });
			    }
             }, function(){
             });
		},
		getInfo: function(deviceId){
			$.get(baseURL + "water/tclientinfo/info/"+deviceId, function(r){
                vm.tClientInfo = r.tClientInfo;

                $('#datetimepicker1').datetimepicker('setDate',vm.tClientInfo.desc1 != "" ? vm.tClientInfo.desc1 : moment(Date.now()).format("YYYY-MM-DD"));
                $('#datetimepicker2').datetimepicker('setDate',vm.tClientInfo.desc6 != "" ? vm.tClientInfo.desc6 : moment(Date.now()).format("YYYY-MM-DD"));
            });
		},
        getDeptTreeLeft: function(){
            $.get(baseURL + "water/waterdept/queryDeptAll", function(r){
                //console.log(r);
                ztree = $.fn.zTree.init($("#deptTreeLeft"), settingLeft, r);
                fuzzySearch('deptTreeLeft','#treeSearchKey',null,true);

                var node = ztree.getNodeByParam("deptId", vm.q.dept);
                if(node != null){
                    ztree.selectNode(node);
                    vm.q.dept = node.deptId;
                }
                var temp=ztree.getNodes();
                getNum(ztree,temp);

                ztree.expandAll(true);
            })
        },
        outxls: function(){
            var total = $("#jqGrid").jqGrid('getGridParam', 'records') + "";
            var dept = vm.q.dept==null ? "" : vm.q.dept+  "";
            location.href = baseURL
                + "water/tclientinfo/export?params="
                + encodeURIComponent(JSON.stringify({key:vm.q.key,value:vm.q.value,dept:dept,limit:total,page:"1"}));

            //console.log(decodeURIComponent(url));
            //location.href = url;
        },
        download: function(){
            var dept = vm.q.dept==null ? "" : vm.q.dept+  "";
            //console.log(dept);
            var url = baseURL + "water/tclientinfo/downloadtemplate?params="
                + encodeURIComponent(JSON.stringify({'key':vm.q.key,'value':vm.q.value,'dept':dept}));
            location.href = url;
        },
openDeptLayer:function(){
            layer.open({
                type: 1,
                offset: '200px',
                skin: 'layui-layer-molv',
                title: "请选择小区",
                area: ['420px', '500px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#deptLayer"),
                btn: ['确定'],
                btn1: function (index) {
                    vm.reload();
                    layer.close(index);
                }
            });
},
        openInfoLayer :function(event){
            vm.getInfo(event.deviceId);

            $.get(baseURL + "water/tdeviceinfo/info/"+event.deviceId, function(r){
                vm.clientDeviceInfo = r.tDeviceInfo;
            });

            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "详细信息处理 【"+event.clientName + "】【" +event.proName+"】",
                area: ['600px', '550px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#clientInfoLayer"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    if (!hasSaveOrUpdatePermission) {
                        layer.close(index);
                        return;
                    }

                    layer.confirm('确定要保存修改的信息吗？', {
                        btn: ['保存','放弃'] //按钮
                    }, function(){
                        vm.tClientInfo.desc1=$('#datetimepicker1').val();
                        vm.tClientInfo.desc6=$('#datetimepicker2').val();

                        $.ajax({
                            type: "POST",
                            url: baseURL + "water/tclientinfo/update",
                            contentType: "application/json",
                            data: JSON.stringify(vm.tClientInfo),
                            success: function(r){
                                if(r.code === 0){
                                    layer.msg(event.clientName + "==信息保存成功！", {icon: 1});
                                    vm.newpage=false;
                                    vm.reload();
                                    layer.close(index);
                                }else{
                                    layer.alert(r.msg);
                                }
                            }
                        });
                    });
                }
            });
        },
		reload: function () {
			vm.showList = true;
			var page = $("#jqGrid").jqGrid('getGridParam','page');

            if(vm.newpage){page = "1";}
            $("#jqGrid").jqGrid('setGridParam',{
                postData:{'key': vm.q.key,'value':vm.q.value,'dept':vm.q.dept},
                page:page
            }).trigger("reloadGrid");
        },
        dateInit: function() {
            now = new Date()
            now.setMinutes(now.getMinutes() - 1)
            startDate = new Date()
            startDate.setDate(startDate.getDate() - 89)
            $('#datetimepicker1').datetimepicker({
                startDate: startDate,
                endDate: new Date(),
                todayBtn: 1,
                autoclose: 1,
                todayHighlight: 1,
                startView: 'month',
                forceParse: 0,
                minView: "day",
                format: 'yyyy/mm/dd hh'
            })

            $('#datetimepicker1').datetimepicker('setDate', now)
            this.startTime = $('#datetimepicker1').val()
            $('#datetimepicker1').datetimepicker()
                .on('hide', (ev) => {
                    this.startTime = $('#datetimepicker1').val()
                })
        },
    },
    mounted: function() {
        //this.dateInit()
    },
    created: function (){
        this.getDeptTreeLeft();
        this.getSearchKeyDict();
    }
});